package com.mall.user.mq;

import com.alibaba.fastjson.JSON;
import com.mall.user.bo.MailInfoBO;
import com.mall.user.dto.UserRegisterRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

@Component
@Slf4j
public class MailProducer {
    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        producer = new DefaultMQProducer("mail_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");

        try {
            producer.start();
        } catch (MQClientException e) {
            log.info("com.mall.user.mq.MailProducer occur exception:" + e);
            e.printStackTrace();
        }
    }

    /*
    实现自动发送验证邮件
     */
    public boolean sendMailMessage(MailInfoBO mailInfoBO) {
        log.info("enter sendMailMessage");
        String data = JSON.toJSONString(mailInfoBO);
        Message message = new Message("mail_producer", data.getBytes(Charset.forName("utf-8")));

        SendResult send = null;
        try {
            send = producer.send(message);
        } catch (MQClientException e) {
            log.info("com.mall.user.mq.MailProducer occur exception:" + e);
            e.printStackTrace();
        } catch (RemotingException e) {
            log.info("com.mall.user.mq.MailProducer occur exception:" + e);
            e.printStackTrace();
        } catch (MQBrokerException e) {
            log.info("com.mall.user.mq.MailProducer occur exception:" + e);
            e.printStackTrace();
        } catch (InterruptedException e) {
            log.info("com.mall.user.mq.MailProducer occur exception:" + e);
            e.printStackTrace();
        }

        if (send != null && SendStatus.SEND_OK.equals(send.getSendStatus())) {
            log.info("send email success");
            return true;
        }
        log.info("send email fail");
        return false;
    }
}
